package com.sheng.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sheng.common.Result;
import com.sheng.common.ResultEnum;
import com.sheng.exception.MyException;
import com.sheng.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 王胜
 * @Date 2022/11/19 17:16
 */
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{

        //创建公共结果类
        Result result = new Result();
        //创建map对象
        Map<Object, Object> map = new HashMap<>();
        //如果是OPTIONS请求 直接放行
        String method = request.getMethod();
        try {
            if(method.equals("OPTIONS")){
                return  true;
            }
            //从请求中获取令牌
            String token = request.getHeader("token");
            //判断token为空或不存在
            if(StringUtils.isEmpty(token) || "null".equals(token) || RedisUtils.get(token) == null){
                log.error("token为空或不存在=>{}",token);
                throw new MyException(ResultEnum.TokenException);
            }
            log.info("token验证通过");
            return true;
        }catch(MyException e){
            log.error(e.toString());
            e.printStackTrace();
            result.setCode(e.getCode());
            result.setMsg(e.getMessage());
        }
        String jsonMap = new ObjectMapper().writeValueAsString(result);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(jsonMap);
        return false;
    }
}